package com.example.gulimall.common.handler;

import com.example.gulimall.common.enums.ServiceCodeEnum;
import com.example.gulimall.common.exceptions.ApiException;
import com.example.gulimall.common.utils.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;

/**
 * <p>@description: 成功处理器  </p>
 * <p>@author: JGD </p>
 * <p>@create: 2020/2/24 15:42 </p>
 * <p>@version : 2.0.0
 **/
@Slf4j
@Component
public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    private static final String BASIC_PREFIX = "basic ";
    @Resource
    private ClientDetailsService clientDetailsService;
    @Resource
    private AuthorizationServerTokenServices authorizationServerTokenServices;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private ObjectMapper objectMapper;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        log.info("登录成功");

        String header = request.getHeader("Authorization");

        if (header == null || !header.toLowerCase().startsWith(BASIC_PREFIX)) {
            log.error("basic 认证失败");
            throw new ApiException(ServiceCodeEnum.SERVER_INTERNAL_ERROR.getCode(),"basic 认证失败");
        }

        String[] tokens = extractAndDecodeHeader(header, request);
        assert tokens.length == 2;

        String clientId = tokens[0];
        String clientSecret = tokens[1];

        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);

        if (clientDetails == null) {
            log.debug("clientId对应的配置信息不存在:" + clientId);
            throw new ApiException(ServiceCodeEnum.SERVER_INTERNAL_ERROR.getCode(),"basic 认证失败");
        } else if (!passwordEncoder.matches(clientSecret, clientDetails.getClientSecret())) {
            log.debug("clientSecret不匹配:" + clientSecret);
            throw new ApiException(ServiceCodeEnum.SERVER_INTERNAL_ERROR.getCode(),"basic 认证失败");
        }

        TokenRequest tokenRequest = new TokenRequest(new HashMap<>(), clientId, clientDetails.getScope(), "custom");

        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);

        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);

        OAuth2AccessToken token = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(ResponseUtil.resultMap(ServiceCodeEnum.SUCCESS.getCode(),token)));
    }
    private String[] extractAndDecodeHeader(String header, HttpServletRequest request) throws IOException {
        byte[] base64Token = header.substring(6).getBytes("UTF-8");
        byte[] decoded;
        try {
            decoded = Base64.getDecoder().decode(base64Token);
        } catch (IllegalArgumentException e) {
            log.debug("Failed to decode basic authentication token", e);
            throw new ApiException(ServiceCodeEnum.SERVER_INTERNAL_ERROR.getCode(),"basic 认证失败");
        }

        String token = new String(decoded, "UTF-8");

        int delim = token.indexOf(":");

        if (delim == -1) {
            log.debug("Invalid basic authentication token");
            throw new ApiException(ServiceCodeEnum.SERVER_INTERNAL_ERROR.getCode(),"basic 认证失败");
        }
        return new String[]{token.substring(0, delim), token.substring(delim + 1)};
    }

}
